#ifndef CTEXTEDITOR_H
#define CTEXTEDITOR_H

#include <QWidget>
#include <QTextEdit>
#include <QPlainTextEdit>
#include <QTextDocument>
#include <QTextBlock>
#include <qpainter.h>
#include "Highlighter.h"
#include <QCompleter>
#include <QAbstractItemView>
#include <QScrollBar>
class CTextEditor : public QPlainTextEdit
{
    Q_OBJECT
public:
    class NumberBar:public QWidget{
    public:
        NumberBar(CTextEditor*editor):QWidget(editor),
            _editor(editor)
        {

        }
        void resizeEvent(QResizeEvent*e)
        {
            QWidget::resizeEvent(e);
        }
        void paintEvent(QPaintEvent*e)
        {
            QPainter painter(this);
            painter.fillRect(e->rect().adjusted(1,1,0,0),QColor("#e8e8e8"));
            QTextBlock block=_editor->firstVisibleBlock();
            int left=_editor->fontMetrics().width("==");
            while (block.isValid())
            {
                int number=block.blockNumber();
                QFont cf(font());
                if(number==_editor->textCursor().blockNumber())
                {
                    cf.setBold(true);
                    cf.setItalic(true);
                }
                else {
                    cf.setBold(false);
                    cf.setItalic(false);
                }
                painter.setFont(cf);
                int top=_editor->blockBoundingGeometry(block).translated(_editor->contentOffset()).top();
                QRect rect(left,top,width(),_editor->fontMetrics().height());
                painter.drawText(rect,QString("%1").arg(number));
                block=block.next();
            }
        }
    protected:
        CTextEditor*_editor;
    };
    explicit CTextEditor(QWidget *parent = nullptr);
    void setText(const QString&txt);
    void setFile(const QString&file);
    void setCompleter(QCompleter*completer);
signals:

public slots:
    void onUpdateRequest(const QRect&rect,int dy);
    void onContentChange();
    void onCursorPositionChanged();
    void insertCompletion(const QString&completion);
protected:
    void keyPressEvent(QKeyEvent *e) override;
    void focusInEvent(QFocusEvent *e) override;
    void resizeEvent(QResizeEvent*e)override;
    void wheelEvent(QWheelEvent*e)override;
    QString textUnderCursor() const;
protected:
    NumberBar*nb;
    float _zoomRange;
    Highlighter::Ptr _highlighter;
    QCompleter*_completer;
};

#endif // CTEXTEDITOR_H
